//
//  FCLoginVC.m
//  FundChain
//
//  Created by 肖浩然的mac on 2018/2/7.
//  Copyright © 2018年 RUIXIN. All rights reserved.
//

#import "FCLoginVC.h"
#import "FCForgetPasswordVC.h"
#import "FCSelectPinVC.h"
#import "FCLeftBarVC.h"
#import "FCHomeVC.h"
#import "XLSlideMenu.h"
#import "FCBaseNavigationVC.h"
#import "FCAddCoinsVC.h"
#import "FCUserModel.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import <IQKeyboardManager/IQKeyboardManager.h>
@interface FCLoginVC ()<UITextFieldDelegate>

/* 邮箱 */
@property (strong, nonatomic)  UITextField *emailField;
/* 密码 */
@property (strong, nonatomic) UITextField *passwordField ;
/* 登陆 */
@property (strong, nonatomic) UIButton *loginBtn;
/* //邮箱错误提示 */
@property (strong, nonatomic)UILabel *errorLabel;
/* 变色的分割线 */
@property (strong, nonatomic)UIView *viewLine1;

/* 数据库保存的所有数据 */
@property (strong, nonatomic) NSArray  *allUserArr;
/* 无数据背景图片 */
@property (strong, nonatomic) UIView *dissView;


/*指纹相关*/
@property(copy,nonatomic)NSString *passFingerToken;//指纹64token
@property(strong,nonatomic)NSString *fingerToken;
/* 指纹按钮 */
@property (strong, nonatomic) UIButton *fingerBtn;
@end

@implementation FCLoginVC

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
   
    NSString *emailStr = [FCLocalUserHelper getUserEmailStr];
    if (emailStr) {
        
        self.emailField.text = emailStr;
    }
    if (self.accountStr) {
        self.emailField.text = self.accountStr;
//        self.passwordField.text = self.passWordStr;
    }
   
   
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.showBackItem = YES;
     [self getCCHStatus];
    [FCLocalUserHelper saveIsMainVC:@"0"];
    self.view.backgroundColor = kWhiteColor;
    self.allUserArr = [FCLocalUserHelper allUserDefaultValue];
//    NSLog(@"%@====%@",self.allUserArr[0],self.allUserArr[1]);
//    FCUserModel *model = self.allUserArr[0];
    //获取加密的fingerToken
    self.passFingerToken = [FCLocalUserHelper getPasswordFingerToken];
    if (!kStringIsEmpty(self.passFingerToken))
    {
        //AES解密
        NSString *pfStr = [FCLocalUserHelper aes256_decryptStr:self.passFingerToken];
        NSString *subStr = [pfStr substringFromIndex:12];
        self.fingerToken = subStr;
        
    }
    //监视邮箱的变化
    [[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(changeValue:) name:@"emailChangeValue"  object:nil];
    [self setupUI];
    
    
    
}

-(void)setupUI{
    //背景图片
    UIImageView *bgImageView = [UIImageView new];
    [self.view addSubview:bgImageView];
    [bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    bgImageView.image = [UIImage imageNamed:@"bg_login"];
    //登陆label
    UILabel *loginLabel = [UILabel new];
    [self.view addSubview:loginLabel];
    [loginLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            if (iPhoneX) {
                make.left.mas_equalTo(32*KScreenWidthScale750);
                make.top.mas_equalTo((100)*KScreenHeightScale1334);
                
            }else{
                make.left.mas_equalTo(32*KScreenWidthScale750);
                make.top.mas_equalTo(100*KScreenHeightScale1334);
                
            }
        }else{
            make.left.mas_equalTo(32*KScreenWidthScale750);
            make.top.mas_equalTo(100*KScreenHeightScale1334);
            
        }
    }];
    loginLabel.text = Localized(@"登录 ");
    loginLabel.font = KOverstrikingfont(52);
    //提示语
    UILabel *hintLabel = [UILabel new];
    [self.view addSubview:hintLabel];
    [hintLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(loginLabel);
        make.top.mas_equalTo(loginLabel.mas_bottom).offset(30*KScreenHeightScale1334);
        make.right.mas_equalTo(-55*KScreenWidthScale750);
    }];
    hintLabel.font = Kfont(28);
    hintLabel.textColor = kGrayColor;
    hintLabel.text = Localized(@"已经注册过？请登录管理您的钱包。");
    hintLabel.numberOfLines = 2;
    //邮箱标题
    UILabel *emailLabel = [UILabel new];
    [self.view addSubview:emailLabel];
    [emailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(loginLabel);
        make.top.mas_equalTo(hintLabel.mas_bottom).offset(120*KScreenHeightScale1334);
        
    }];
    emailLabel.font = Kfont(32);
    emailLabel.textColor = kGrayColor;
    emailLabel.text = Localized(@"邮箱");
    //输入邮箱
    UITextField *emailField = [UITextField new];
    self.emailField = emailField;
    [self.view addSubview:emailField];
    [emailField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(emailLabel.mas_bottom).offset(30*KScreenHeightScale1334);
        make.left.mas_equalTo(loginLabel);
        make.right.mas_equalTo(-30*KScreenWidthScale750);
    }];
    emailField.delegate = self;
    emailField.keyboardType = UIKeyboardTypeEmailAddress;
    [emailField becomeFirstResponder];
    //分割线
    UIView *viewLine1 =[UIView new];
    self.viewLine1 = viewLine1;
    [self.view addSubview:viewLine1];
    [viewLine1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(emailField);
        make.top.mas_equalTo(emailField.mas_bottom);
        make.height.mas_equalTo(1);
    }];
    viewLine1.backgroundColor =kLineColor;
    //邮箱错误提示
    UILabel *errorLabel = [UILabel new];
    self.errorLabel = errorLabel;
    [self.view addSubview:errorLabel];
    [errorLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(loginLabel);
        make.top.mas_equalTo(viewLine1.mas_bottom).offset(12*KScreenHeightScale1334);
    }];
    errorLabel.textColor = kwarningColor;
    errorLabel.font = Kfont(24);
    errorLabel.text = Localized(@"电子邮件地址不存在，请重新输入。");
    errorLabel.hidden = YES;
    //密码标题
    UILabel *passwordLabel = [UILabel new];
    [self.view addSubview:passwordLabel];
    [passwordLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(loginLabel);
        make.top.mas_equalTo(viewLine1.mas_bottom).offset(80*KScreenHeightScale1334);
        
    }];
    passwordLabel.font = Kfont(32);
    passwordLabel.textColor = kGrayColor;
    passwordLabel.text = Localized(@"密码");
    
   
    
    //输入密码
    UITextField *passwordField = [UITextField new];
    self.passwordField = passwordField;
    [self.view addSubview:passwordField];
    [passwordField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(passwordLabel.mas_bottom).offset(30*KScreenHeightScale1334);
        make.left.mas_equalTo(loginLabel);
        make.right.mas_equalTo(-30*KScreenWidthScale750);
    }];
    passwordField.delegate = self;
    passwordField.secureTextEntry = YES;
   
    //分割线
    UIView *viewLine2 =[UIView new];
    [self.view addSubview:viewLine2];
    [viewLine2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(passwordField);
        make.top.mas_equalTo(passwordField.mas_bottom);
        make.height.mas_equalTo(1);
    }];
    viewLine2.backgroundColor =kLineColor;
    
    //忘记密码按钮
    UIButton *forgetPasswordBtn = [UIButton new];
    [self.view addSubview:forgetPasswordBtn];
    [forgetPasswordBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(passwordField);
        make.top.mas_equalTo(viewLine2.mas_bottom).offset(20*KScreenHeightScale1334);
    }];
    [forgetPasswordBtn setTitle:Localized(@"忘记密码?") forState:UIControlStateNormal];
    forgetPasswordBtn.titleLabel.font = Kfont(28);
    [forgetPasswordBtn setTitleColor:kDarkBlackColor forState:UIControlStateNormal];
    
    //登陆按钮
    UIButton *loginBtn = [UIButton new];
    self.loginBtn = loginBtn;
    [self.view addSubview:loginBtn];
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30*KScreenWidthScale750);
        make.right.mas_equalTo(-30*KScreenWidthScale750);
        make.bottom.mas_equalTo(-100*KScreenHeightScale1334);
        make.height.mas_equalTo(112*KScreenHeightScale1334);
    }];
    loginBtn.layer.cornerRadius = 5.0;
    loginBtn.layer.masksToBounds = YES;
    loginBtn.titleLabel.font = KOverstrikingfont(36);
    [loginBtn setTitle:Localized(@"登录") forState:(UIControlStateNormal)];
    [loginBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [loginBtn setBackgroundColor:kLightblueColor];
    
    //指纹按钮
    UIButton *fingerBtn = [UIButton new];
    self.fingerBtn = fingerBtn;
    [self.view addSubview:fingerBtn];
    [fingerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(loginBtn.mas_top).offset(-20);
        make.centerX.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    [fingerBtn setBackgroundImage:[UIImage imageNamed:@"finger"] forState:(UIControlStateNormal)];
    if (!kStringIsEmpty(self.fingerToken)) {
        self.fingerBtn.hidden = NO;
    }else{
        self.fingerBtn.hidden = YES;
    }
    
    
    
    //事件
    [emailField addTarget:self action:@selector(emailTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    [emailField addTarget:self action:@selector(emailTextFieldDidEnd:) forControlEvents:UIControlEventEditingDidEnd];
    [passwordField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [loginBtn addTarget:self action:@selector(loginBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [forgetPasswordBtn addTarget:self action:@selector(forgetPasswordBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
     [fingerBtn addTarget:self action:@selector(fingerBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
}
#pragma mark-指纹登陆
-(void)setFingerLogin{
    
    __weak __typeof(self)wself = self;
    NSString *email =self.emailField.text.trimWhitespace;
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:1];
    [dict setObject:email forKey:@"email"];
    [dict setObject:self.fingerToken forKey:@"fingerToken"];
    [self showChrysanthemumAlert:nil];
    NSString *url = Login_in_email_finger_URL;
    [FCSharedNetworkTool POSTWithURLString:url parameters:dict success:^(id responseObject) {
        if (responseObject) {
            if ([responseObject[@"code"] integerValue] == 200) {
                
                [FCLocalUserHelper saveXidStr:responseObject[@"result"][@"XID"]];
                [FCLocalUserHelper saveTokenStr:responseObject[@"result"][@"token"]];
                 [FCLocalUserHelper saveUserEmailStr:self.emailField.text.trimWhitespace];
                [FCLocalUserHelper saveLoginStates:@"1"];
                [wself loadUserInfoDataWith:responseObject[@"result"][@"token"] :responseObject[@"result"][@"XID"]];
                
            }else if ([responseObject[@"code"] integerValue] == 404){
                [self hideProgress];
                [self showAlert:Localized(@"邮箱未注册")];
                
            }else if ([responseObject[@"code"] integerValue] == 400){
                
                [self hideProgress];
                [self showAlert:Localized(@"指纹已失效，请用密码登陆")];
                [FCLocalUserHelper cleanPasswordFingerToken];
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.fingerBtn.hidden = YES;
                });
            }
        }
        
        
    } faile:^(NSError *error) {
        
        
        
    }];
    
    
}

-(void)fingerBtnClick:(UIButton*)sender{
    
    __weak typeof(self) weakSelf = self;
    
    LAContext *myContext = [[LAContext alloc] init];
    // 这个属性是设置指纹输入失败之后的弹出框的选项
    myContext.localizedFallbackTitle = @"";
    if (is_IOS_10)
    {
        myContext.localizedCancelTitle=Localized(@"取消");
    }
    
    NSError *authError = nil;
    NSString *myLocalizedReasonString = Localized(@"请验证已有指纹，用于登入");
    // 判断用户手机系统是否是 iOS 8.0 以上版本
    if (!([UIDevice currentDevice].systemVersion.floatValue >= 8.0)) {
        NSLog(@"系统不支持");
        return;
    }
    
    // MARK: 判断设备是否支持指纹识别
    if ([myContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:&authError])
    {
        [myContext evaluatePolicy:LAPolicyDeviceOwnerAuthentication localizedReason:myLocalizedReasonString reply:^(BOOL success, NSError * _Nullable error) {
            if(success)
            {
                NSLog(@"指纹认证成功");
                //设置指纹认证
                [weakSelf setFingerLogin];
                
            }
            else
            {
                
                NSLog(@"指纹认证失败，%@",error.description);
                
                NSLog(@"%ld", (long)error.code); // 错误码 error.code
                switch (error.code)
                {
                    case LAErrorAuthenticationFailed: // Authentication was not successful, because user failed to provide valid credentials
                    {
                        [self showAlert:Localized(@"尝试次数过多，请稍后重试")];
                        
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [weakSelf.navigationController popViewControllerAnimated:YES];
                        });
                        NSLog(@"授权失败"); // -1 连续三次指纹识别错误
                    }
                        break;
                    case LAErrorUserCancel: // Authentication was canceled by user (e.g. tapped Cancel button)
                    {
                       
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [weakSelf.navigationController popViewControllerAnimated:YES];
                        });
                        NSLog(@"用户取消验证Touch ID"); // -2 在TouchID对话框中点击了取消按钮
                        
                    }
                        break;
                    case LAErrorUserFallback: // Authentication was canceled, because the user tapped the fallback button (Enter Password)
                    {
                        
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            NSLog(@"用户选择输入密码，切换主线程处理"); // -3 在TouchID对话框中点击了输入密码按钮
                        }];
                        
                    }
                        break;
                    case LAErrorSystemCancel: // Authentication was canceled by system (e.g. another application went to foreground)
                    {
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [weakSelf.navigationController popViewControllerAnimated:YES];
                        });
                        NSLog(@"取消授权，如其他应用切入，用户自主"); // -4 TouchID对话框被系统取消，例如按下Home或者电源键
                    }
                        break;
                    case LAErrorPasscodeNotSet: // Authentication could not start, because passcode is not set on the device.
                        
                    {
                        [self showAlert:Localized(@"设备系统未设置密码")];
                        
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [weakSelf.navigationController popViewControllerAnimated:YES];
                        });
                        NSLog(@"设备系统未设置密码"); // -5
                    }
                        break;
                    case LAErrorTouchIDNotAvailable: // Authentication could not start, because Touch ID is not available on the device
                    {
                        [self showAlert:Localized(@"设备未设置Touch ID")];
                       
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [weakSelf.navigationController popViewControllerAnimated:YES];
                        });
                        NSLog(@"设备未设置Touch ID"); // -6
                    }
                        break;
                    case LAErrorTouchIDNotEnrolled: // Authentication could not start, because Touch ID has no enrolled fingers
                    {
                        
                        NSLog(@"用户未录入指纹"); // -7
                    }
                        break;
                        
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0
                    case LAErrorTouchIDLockout: //Authentication was not successful, because there were too many failed Touch ID attempts and Touch ID is now locked. Passcode is required to unlock Touch ID, e.g. evaluating LAPolicyDeviceOwnerAuthenticationWithBiometrics will ask for passcode as a prerequisite 用户连续多次进行Touch ID验证失败，Touch ID被锁，需要用户输入密码解锁，先Touch ID验证密码
                    {
                        [self showAlert:Localized(@"Touch ID被锁，需要用户输入密码解锁")];
                       
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [weakSelf.navigationController popViewControllerAnimated:YES];
                        });
                        NSLog(@"Touch ID被锁，需要用户输入密码解锁"); // -8 连续五次指纹识别错误，TouchID功能被锁定，下一次需要输入系统密码
                        //跳转到系统密码设置界面
                        
                        
                        
                    }
                        break;
                    case LAErrorAppCancel: // Authentication was canceled by application (e.g. invalidate was called while authentication was in progress) 如突然来了电话，电话应用进入前台，APP被挂起啦");
                    {
                        
                        NSLog(@"用户不能控制情况下APP被挂起"); // -9
                    }
                        break;
                    case LAErrorInvalidContext: // LAContext passed to this call has been previously invalidated.
                    {
                        
                        NSLog(@"LAContext传递给这个调用之前已经失效"); // -10
                    }
                        break;
#else
#endif
                    default:
                    {
                        
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            NSLog(@"其他情况，切换主线程处理");
                        }];
                        break;
                    }
                }
            }
        }];
    }
    else
    {
        NSLog(@"设备不支持指纹");
        NSLog(@"%ld", (long)authError.code);
        
        
        switch (authError.code)
        {
            case LAErrorTouchIDNotEnrolled:
            {
                
                [self showAlert:Localized(@"身份验证无法启动,因为没有登记的手指触摸ID")];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                });
                
                NSLog(@"Authentication could not start, because Touch ID has no enrolled fingers");
                break;
            }
            case LAErrorPasscodeNotSet:
            {
                [self showAlert:Localized(@"身份验证无法启动,因为密码没有设置在设备上")];
               
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                });
                NSLog(@"Authentication could not start, because passcode is not set on the device");
                break;
            }
            default:
            {
                [self showAlert:Localized(@"TouchID不可用，需要用户输入密码解锁")];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                });
                NSLog(@"TouchID not available");
                break;
            }
        }
    }
    
    
}
#pragma mark-登陆
-(void)loginBtnClick:(UIButton*)sender{

//    if (sender) {
//        FCAddCoinsVC *vc = [FCAddCoinsVC new];
//        [self.navigationController pushViewController:vc animated:YES];
//    }
    if (self.emailField.text.trimWhitespace.length <= 0 || self.passwordField.text.trimWhitespace.length <= 0 ) {
        return;
    }
    [self showChrysanthemumAlert:nil];
    if (self.passwordField.text.trimWhitespace.length <6 || self.passwordField.text.trimWhitespace.length >16) {
        [self showAlert:Localized(@"密码必须为6-16位字符，区分大小写")];
        return;
    }
    //    [dic setObject:@"229659522@qq.com" forKey:@"email"];
    //    [dic setObject:@"123456" forKey:@"passWord"];
    
    
    NSString *url = [NSString stringWithFormat:@"%@",Login_URL];
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:1];
    [dic setObject:self.emailField.text.trimWhitespace forKey:@"email"];
    [dic setObject:self.passwordField.text.trimWhitespace forKey:@"passWord"];
    
    [FCSharedNetworkTool POSTWithURLString:url parameters:dic success:^(id responseObject) {
        NSLog(@"res:%@",responseObject);
        NSDictionary *dict = responseObject;
        NSNumber *str = dict[@"code"];
        NSNumber *two = [[NSNumber alloc]initWithLong:200];
        NSNumber *free = [[NSNumber alloc]initWithLong:400];
        NSNumber *free1 = [[NSNumber alloc]initWithLong:404];
        if (str == two) {
            [self hideProgress];
            
            //保存XID和token
            [FCLocalUserHelper saveXidStr:dict[@"result"][@"XID"]];
            [FCLocalUserHelper saveTokenStr:dict[@"result"][@"token"]];
            
            [self loadUserInfoDataWith:dict[@"result"][@"token"] :dict[@"result"][@"XID"]];
            
            
        }else if (str == free){
            [self hideProgress];
            [self showAlert:Localized(@"电子邮件和密码不匹配，请重新输入。")];
        }else if (str == free1){
            [self hideProgress];
            [self showAlert:Localized(@"电子邮件地址不存在，请重新输入。")];
        }else if ([responseObject[@"code"] integerValue] == 407){
            [self hideProgress];
            [self showAlert:Localized(@"电子邮件地址不存在，请重新输入。")];
        }
        
        
    } faile:^(NSError *error) {
        [self hideProgress];
        if (error) {
            NSLog(@"%@",error);
        }
        
        __weak __typeof(self)wself = self;
        [FCLocalUserHelper hasNetwork:^(bool has) {
            if (has)
            {
                [wself showAlert:Localized(@"网络请求失败")];
            } else
            {
                [wself showAlert:Localized(@"网络未连接")];
            }
        }];
        
    }];
    
    
    
}
-(void)loadUserInfoDataWith:(NSString*)token:(NSString*)xidStr{
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:1];
        NSDate* data = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval timeInterval = [data timeIntervalSince1970]*1000;
        //获取时间戳
        NSString *timeString = [NSString stringWithFormat:@"%ld",(long)timeInterval];
        NSString * postSign = [NSString stringWithFormat:@"%@%@%@",token,timeString,xidStr];
        
        [dict setObject:[FCLocalUserHelper sha1:postSign] forKey:@"sign"];
        [dict setObject:timeString forKey:@"time"];
    [dict setObject:xidStr forKey:@"XID"];
    
    NSString *url = Get_my_information_URL;
    
    [FCSharedNetworkTool POSTWithURLString:url parameters:dict success:^(id responseObject) {
        if(responseObject){
            NSLog(@"%@",responseObject);
            NSDictionary *dic = responseObject;
            if([dic[@"code"] integerValue] == 200){
                FCUserModel *model = [FCUserModel mj_objectWithKeyValues:responseObject[@"result"]];
                model.XID = xidStr;
                [FCLocalUserHelper saveFMDBUserInfoData:model];
                //保存登陆的email账号
                [FCLocalUserHelper saveUserEmailStr:self.emailField.text.trimWhitespace];
//                NSString *str = [FCLocalUserHelper getLoginState];
                if ([[FCLocalUserHelper getLoginState] isEqualToString:@"1"]) {
                    
                    
                    if ([model.pinExists isEqualToString:@"1"]) {
                        
                            [self hideProgress];
                            //跳转主控制器
                            [self showAlert:Localized(@"登录成功")];
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                [FCLocalUserHelper saveLoginStates:@"1"];
                                [FCLocalUserHelper pushMainTabbarController];
                                
                            });
                        
                        
                    }
                    
                }else{
                    
                    if ([model.pinExists isEqualToString:@"1"]) {
                       [self pushAddCoinsVCWith:token :xidStr];
                        
                    }
                    else {
                        
                        FCSelectPinVC *vc = [FCSelectPinVC new];
                        [self.navigationController pushViewController:vc animated:NO];
                        
                    }
                    
                    
                }
               
               
                
            }else if ([dic[@"code"] integerValue] == 405){
                //账号在其他设备登陆
//                [self alertController];
            }
            
        }
        
    } faile:^(NSError *error) {
        
        if(error){
            NSLog(@"%@",error);
        }
        
    }];
    
}

-(void)pushAddCoinsVCWith:(NSString*)token:(NSString*)xidStr{
    
    //url
    NSString *url = Load_my_wallet_type_URL;
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:1];
    NSDate* data = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval timeInterval = [data timeIntervalSince1970]*1000;
    //获取时间戳
    NSString *timeString = [NSString stringWithFormat:@"%ld",(long)timeInterval];
    NSString * postSign = [NSString stringWithFormat:@"%@%@%@",token,timeString,xidStr];
    [dict setObject:[FCLocalUserHelper sha1:postSign] forKey:@"sign"];
    [dict setObject:timeString forKey:@"time"];
    [dict setObject:xidStr forKey:@"XID"];
    
    [FCSharedNetworkTool POSTWithURLString:url parameters:dict success:^(id responseObject) {
        if (responseObject) {
            NSLog(@"%@",responseObject);
            if ([responseObject[@"code"] integerValue] == 200) {
                //保存添加的货币种类
                FCWalletTypesModel *model = [FCWalletTypesModel mj_objectWithKeyValues:responseObject[@"result"]];
                NSLog(@"%@",model.walletTypes);
                NSString *xidStr = [FCLocalUserHelper getXidStr];
                model.XID = xidStr;
                [FCLocalUserHelper saveFMDBWalletTypesData:model];
               
                    [self showAlert:Localized(@"登录成功")];
                    [FCLocalUserHelper saveLoginStates:@"1"];
                    [FCLocalUserHelper pushMainTabbarController];
                
                
            }
            
            
            
        }
        
    } faile:^(NSError *error) {
        if (error) {
            NSLog(@"%@",error);
        }
        
    }];
}
#pragma mark-textFieldDelegate
-(void)emailTextFieldDidEnd:(UITextField *)textField{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"emailChangeValue" object:textField];
    [textField resignFirstResponder];
     NSString *user = [FCLocalUserHelper getUserEmailStr];
    if (![self.emailField.text.trimWhitespace isEqualToString:user]) {
        [FCLocalUserHelper cleanLoginState];
    }
}
-(void)emailTextFieldDidChange:(UITextField *)textField{
    
    self.viewLine1.backgroundColor = HEXCOLOR(0x006fb6);
    if (textField.text.trimWhitespace.length ==0) {
        self.viewLine1.backgroundColor = kLineColor;
    }
    
    
}

#pragma mark-通过监测邮箱来是否显示指纹功能

-(void)fingerBtnFromEmailHide:(NSString *)key Value:(NSString *)value{
    //  定义一个property来存放属性名，定义一个value来存放值
    NSString *countryNameProperty = key;
    
    //  该谓词的作用是如果元素中property属性含有值value时就取出放入新的数组内，这里是name包含Jack
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"%K LIKE %@", countryNameProperty, value];
    NSArray *newArray = [self.allUserArr filteredArrayUsingPredicate:pred];
    if (newArray.count==1)
    {
        FCUserModel *userModel = newArray[0];
        
        NSString *fingerTokenStr = [FCLocalUserHelper getPasswordFingerToken:userModel.XID];
        if (!kStringIsEmpty(fingerTokenStr))
        {
            if ([countryNameProperty isEqualToString:@"email"])
            {
                self.fingerBtn.hidden = false;
                //AES解密
                NSString *pfStr = [FCLocalUserHelper aes256_decryptStr:fingerTokenStr];
                NSString *subStr = [pfStr substringFromIndex:12];
                self.fingerToken = subStr;
                
            }else{
                self.fingerBtn.hidden = YES;
            }
            
            
        }else{
            self.fingerBtn.hidden = YES;
        }
    }else if (newArray.count>1){
        if ([countryNameProperty isEqualToString:@"email"])
        {
            [newArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                FCUserModel *model = [FCUserModel mj_objectWithKeyValues:obj];
                
                NSString *fingerTokenStr = [FCLocalUserHelper getPasswordFingerToken:model.XID];
                if (!kStringIsEmpty(fingerTokenStr))
                {
                    self.fingerBtn.hidden = false;
                    //AES解密
                    NSString *pfStr = [FCLocalUserHelper aes256_decryptStr:fingerTokenStr];
                    NSString *subStr = [pfStr substringFromIndex:12];
                    self.fingerToken = subStr;
                    *stop = YES;
                }else
                {
                    self.fingerBtn.hidden = YES;
                }
                
            }];
            
        }else
        {
            self.fingerBtn.hidden = YES;
        }
        
    }else if (newArray.count==0)
    {
        self.fingerBtn.hidden = YES;
    }
    
}

-(void)changeValue:(NSNotification *)notification {
    UITextField *textField = notification.object;
    
    //要实现的监听方法操作
    if (self.emailField == textField) {
        
        if ([FCLocalUserHelper isValidateEmail:textField.text]) {
            
            self.errorLabel.hidden = YES;
        }else{
            self.errorLabel.hidden = NO;
        }
    }
    //通过邮箱来判断是否显示指纹功能
    if (self.emailField == textField) {
        
        [self fingerBtnFromEmailHide:@"email" Value:[textField.text lowercaseString]];
    }
}
-(void)textFieldDidChange:(UITextField *)textField{
    
    
    if(self.passwordField == textField ){
        if (textField.text.trimWhitespace.length > 16) {
            textField.text = [textField.text substringToIndex:16];
            
            
        }
    }
    if(self.passwordField == textField ){
        if (self.emailField.text.trimWhitespace.length > 0 && self.passwordField.text.trimWhitespace.length > 0) {
            
            [self.loginBtn setBackgroundColor:kRedOrangeColor];
            
        }else{
            [self.loginBtn setBackgroundColor:kLightblueColor];
        }
        
        
    }
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //移除第一响应
    [self.emailField resignFirstResponder];
    [self.passwordField resignFirstResponder];
    
}
#pragma mark-忘记密码
-(void)forgetPasswordBtnClick:(UIButton*)sender{
    
    FCForgetPasswordVC *vc = [FCForgetPasswordVC new];
    [self.navigationController pushViewController:vc animated:NO];
    
}
-(void)getCCHStatus{
    
    NSString *url = @"https://app.fund-chain.io/Fundchain/index.php/Api/Base/is_show_coin_1_0";
    [FCSharedNetworkTool POSTWithURLString:url parameters:nil success:^(id responseObject) {
        if (responseObject) {
            if ([responseObject[@"code"] integerValue] == 200) {
                NSLog(@"CCH是%@",responseObject[@"result"][@"show"]);
                NSString *res = [NSString stringWithFormat:@"%@",responseObject[@"result"][@"show"]];
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    FCCCHStatusModel *model = [FCCCHStatusModel new];
                    model.statusStr = res;
                    [FCLocalUserHelper saveCCHStatus:model];
                });
                
                
            }
        }
        
        
    } faile:^(NSError *error) {
        
        
    }];
}
@end

